# -*- coding: utf-8 -*-

from flask import request, abort, url_for
from google.appengine.ext import db
from dicthash.utils import project2dict
from dicthash.decorators import html_it, json_it, glue_GET_POST

from ..backends.working.models import Note, Lenta
from ..backends.working.exceptions import OrphanEntityError, BadParentError
from ..forms import NoteForm
from .lenta import _fetch_lenta

__all__ = ['add_note', 'view_note', 'edit_note', 'delete_note']


NoteProperties = ['id', 'namespace', 'lenta_id', 'title', 'twit', 'body', 'pubDate', 'tags', 'owner_key']

def _fetch_note(note_id, lenta_id, namespace=None):
    """ """
    parent_key = db.Key.from_path('Lenta', lenta_id, namespace=namespace)
    key = db.Key.from_path('Note', note_id, parent=parent_key, namespace=namespace)
    return Note.get(key) or abort(404)

def _proj_n(note):
    """ """
    return project2dict(note, NoteProperties)


def _add_note_GET(lenta_id):
    """ """
    _fetch_lenta(lenta_id)
    return {}

def _add_note_POST(lenta_id):
    """
    Add new `Note` entity.
    """
    _fetch_lenta(lenta_id)
    
    form = NoteForm(request.form)
    if form.is_valid():
        note = Note.new(parent=db.Key.from_path('Lenta', lenta_id), **form.cleaned_data)
        try:
            note.put()
        except (OrphanEntityError, BadParentError):
            abort(404)
        return dict(note=_proj_n(note))
    else:
        return dict(errors=form.errors, note=request.form)
    
add_note = html_it ('/lenta/note/add_note.html', '/lenta/note/add_note_ok.html') \
                                (glue_GET_POST(_add_note_GET, _add_note_POST))


def _view_note(note_id, lenta_id, namespace):
    """
    Get `Note` entity from datastore.
    """
    return dict(note=_proj_n(_fetch_note(note_id, lenta_id, namespace))) 

view_note = html_it ('/lenta/note/view_note.html') (_view_note)
view_note_json = json_it () (_view_note)


def _edit_note_GET(note_id, lenta_id):
    """ """
    return dict(note=NoteForm(_proj_n(_fetch_note(note_id, lenta_id))).htmlize())

def _edit_note_POST(note_id, lenta_id):
    """ """
    note = _fetch_note(note_id, lenta_id)
        
    form = NoteForm(request.form)
    if form.is_valid():
        note.update(**form.cleaned_data)
        return dict(note=_proj_n(note))
    else:
        return dict(errors=form.errors, note=request.form)
    
edit_note = html_it ('/lenta/note/edit_note.html', '/lenta/note/edit_note_ok.html') \
                                (glue_GET_POST(_edit_note_GET, _edit_note_POST))


def _delete_note_GET(note_id, lenta_id):
    """ """
    return dict(note=_proj_n(_fetch_note(note_id, lenta_id)))

def _delete_note_POST(note_id, lenta_id):
    """ """
    note = _fetch_note(note_id, lenta_id)
    note.delete()
    return dict()

delete_note = html_it ('/lenta/note/delete_note.html', '/lenta/note/delete_note_ok.html') \
                                (glue_GET_POST(_delete_note_GET, _delete_note_POST))
